package com.tianshuo.controller;

import com.tianshuo.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * @author tianshuo
 */
@RequestMapping("/index")
@Controller
public class IndexController {

    /**
     * 当全局的异常处理和controller类中的异常处理都有时，优先类中的异常处理
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ModelAndView error(Exception exception) {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error");
        modelAndView.addObject("ex", exception);

        return modelAndView;
    }

    @RequestMapping()
    public String show() {

        int a = 1 / 0;
        return "index";
    }

    /**
     * page
     * @return
     */
    @RequestMapping("/test")
    public String page() {
        return "test";
    }

    /**
     * 返回欢迎页面
     * @return
     */
    @RequestMapping({"/home", "/h"})
    public String home() {
        return "home";
    }


    @RequestMapping("/restful/{id}")
    @ResponseBody
    public String restful(@PathVariable("id") String id) {
        System.out.println(id);
        return id;
    }

    /**
     * 返回json数据
     * @return
     */
    @RequestMapping("/user")
    @ResponseBody
    public List<User> user() {
        List<User> list = new ArrayList<>();
        User user = new User("1","tianshuo",30);
        User user1 = new User("2","tianyulin",3);
        User user2 = new User("3","tianyuhao",5);
        User user3 = new User("4","liuyang",31);
        list.add(user);
        list.add(user1);
        list.add(user2);
        list.add(user3);
        return list;
    }

    /**
     * 如果返回值为null或者void时，springmvc会默认跳转到与请求路径一样的view中，如hp.jsp
     */
    @RequestMapping("/hp")
    public void hp() {
        System.out.println("hp");
    }



}
